/**
 * Filename: FrePhotoView.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/13 16:47
 */
package com.github.postsanf.yinian.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.AbstractDraweeController;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.DraweeHolder;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.image.CloseableStaticBitmap;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.nostra13.universalimageloader.core.ImageLoader;

import uk.co.senab.photoview.PhotoView;

public class FrePhotoView extends PhotoView {
    int screenWidthPixels;
    int screenHeightPixels;
    private DraweeHolder<GenericDraweeHierarchy> mDraweeHolder;

    public FrePhotoView(Context context) {
        this(context, null);
    }

    public FrePhotoView(Context context, AttributeSet attr) {
        this(context, attr, 0);
    }

    public FrePhotoView(Context context, AttributeSet attr, int defStyle) {
        super(context, attr, defStyle);
        screenWidthPixels = DisplayUtils.getScreenWidthPixels((Activity) context);
        screenHeightPixels = DisplayUtils.getScreenHeightPixels((Activity) context);
        selfInit();
    }

    private void selfInit() {
        if (mDraweeHolder == null) {
            final GenericDraweeHierarchy hierarchy = new GenericDraweeHierarchyBuilder(getResources())
                    .setProgressBarImage(new LoadingProgressDrawable(getContext())).build();
            mDraweeHolder = DraweeHolder.create(hierarchy, getContext());
        }
    }

    public static final int OPGL_MAX_TEXTURE = 4000;

    private boolean isBigPicture(Bitmap bitmap) {
        //penGLRenderer: Bitmap too large to be uploaded into a texture (299x7200, max=4096x4096)
        return bitmap.getHeight() >= OPGL_MAX_TEXTURE || bitmap.getWidth() >= OPGL_MAX_TEXTURE;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mDraweeHolder.onDetach();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mDraweeHolder.onAttach();
    }

    @Override
    protected boolean verifyDrawable(Drawable dr) {
        super.verifyDrawable(dr);
        return dr == mDraweeHolder.getHierarchy().getTopLevelDrawable();
    }

    @Override
    public void onStartTemporaryDetach() {
        super.onStartTemporaryDetach();
        mDraweeHolder.onDetach();
    }

    @Override
    public void onFinishTemporaryDetach() {
        super.onFinishTemporaryDetach();
        mDraweeHolder.onAttach();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mDraweeHolder.onTouchEvent(event) || super.onTouchEvent(event);
    }

    public void setImageUri(final String uri, ResizeOptions options, final Context mContext) {
        final ImageRequest imageRequest = ImageRequestBuilder
                .newBuilderWithSource(Uri.parse(uri))
                .setResizeOptions(options)
                .setProgressiveRenderingEnabled(true)
                .setAutoRotateEnabled(true)
                .build();
        final ImagePipeline imagePipeline = Fresco.getImagePipeline();
        final DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, this);
        final AbstractDraweeController controller = Fresco.newDraweeControllerBuilder()
                .setOldController(mDraweeHolder.getController())
                .setImageRequest(imageRequest)
                .setAutoPlayAnimations(true)
                .setControllerListener(new BaseControllerListener<ImageInfo>() {
                    @Override
                    public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                        super.onFinalImageSet(id, imageInfo, animatable);
                        CloseableReference<CloseableImage> imageCloseableReference = null;
                        try {
                            imageCloseableReference = dataSource.getResult();
                            if (imageCloseableReference != null) {
                                CloseableImage image = imageCloseableReference.get();
                                if (image != null && image instanceof CloseableStaticBitmap) {
                                    CloseableStaticBitmap closeableStaticBitmap = (CloseableStaticBitmap) image;
                                    final Bitmap bitmap = closeableStaticBitmap.getUnderlyingBitmap();
                                    if (bitmap != null) {
                                        if (bitmap.getWidth() > bitmap.getHeight()) {
                                            Glide.with(mContext).load(StringUtils.repaceImgUrl(YNUrlHelper.getStatusUrl(mContext, uri))).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(FrePhotoView.this);
                                            return;
                                        } else {
                                            setImageBitmap(bitmap);
                                        }
                                        // 如果是长图，让其宽度放大至与屏幕等宽
                                        if (screenWidthPixels * bitmap.getHeight() >= screenHeightPixels * bitmap.getWidth()) {
                                            setScaleType(ScaleType.CENTER_CROP);
                                        }
                                        if (isBigPicture(bitmap)) {
                                            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                                        }
                                    }
                                }
                            }
                        } finally {
                            dataSource.close();
                            CloseableReference.closeSafely(imageCloseableReference);
                        }
                    }
                })
                .build();
        mDraweeHolder.setController(controller);
        setImageDrawable(mDraweeHolder.getTopLevelDrawable());
    }

    public void setImageUri3(final String uri, final Context mContext) {
        ImageRequest imageRequest = ImageRequestBuilder
                .newBuilderWithSource(Uri.parse(uri))
                .setAutoRotateEnabled(true)
                .build();
        final DataSource<CloseableReference<CloseableImage>> dataSource = Fresco.getImagePipeline().fetchDecodedImage(imageRequest, this);
        final AbstractDraweeController controller = Fresco.newDraweeControllerBuilder()
                .setOldController(mDraweeHolder.getController())
                .setImageRequest(imageRequest)
                .setAutoPlayAnimations(true)
                .setControllerListener(new BaseControllerListener<ImageInfo>() {
                    @Override
                    public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                        super.onFinalImageSet(id, imageInfo, animatable);
                        CloseableReference<CloseableImage> imageCloseableReference = null;
                        try {
                            imageCloseableReference = dataSource.getResult();
                            if (imageCloseableReference != null) {
                                final CloseableImage image = imageCloseableReference.get();
                                if (image != null && image instanceof CloseableStaticBitmap) {
                                    CloseableStaticBitmap closeableStaticBitmap = (CloseableStaticBitmap) image;
                                    final Bitmap bitmap = closeableStaticBitmap.getUnderlyingBitmap();
                                    if (bitmap != null) {
                                        Log.i("xjs", "bitmapnnnnnnnnn");
//                                        setImageBitmap(bitmap);
//                                        ImageRequest imageRequest2 = ImageRequestBuilder
//                                                .newBuilderWithSource(Uri.parse(uri))
//                                                .setAutoRotateEnabled(true)
//                                                .build();
//                                        DraweeController controller = Fresco.newDraweeControllerBuilder()
//                                                .setImageRequest(imageRequest2)
//                                                .setOldController(mDraweeHolder.getController())
//                                                .build();
//                                        mDraweeHolder.setController(controller);
                                        ImageLoader.getInstance().displayImage(uri, FrePhotoView.this);
//                                        Glide.with(mContext).load(uri).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(FrePhotoView.this);
                                        // 如果是长图，让其宽度放大至与屏幕等宽
                                        if (screenWidthPixels * bitmap.getHeight() >= screenHeightPixels * bitmap.getWidth()) {
                                            setScaleType(ScaleType.CENTER_CROP);
                                        }
                                        if (isBigPicture(bitmap)) {
                                            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                                        }
                                    }
                                }
                            }
                        } finally {
                            dataSource.close();
                            CloseableReference.closeSafely(imageCloseableReference);
                        }
                    }
                })
                .build();
        mDraweeHolder.setController(controller);
//        setImageDrawable(mDraweeHolder.getTopLevelDrawable());
    }

    public void setImageUri2(final Context mContext, final String uri, ResizeOptions options) {
        Glide.with(mContext).load(uri).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                // 如果是长图，让其宽度放大至与屏幕等宽
                Log.i("xjs", "bitmap.getHeight==>" + bitmap.getHeight());
                Log.i("xjs", "bitmap.getWidth==>" + bitmap.getWidth());
                if (screenWidthPixels * bitmap.getHeight() >= screenHeightPixels * bitmap.getWidth()) {
                    setScaleType(ScaleType.CENTER_CROP);
                }
                if (isBigPicture(bitmap)) {
                    setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                }
//                    Glide.with(mContext)
//                            .load(uri)
//                            .centerCrop()
//                            .into(FrePhotoView.this);
                Log.i("xjs", "ttt");
                setImageBitmap(bitmap);
            }
        });
    }

}